package cn.qayy.service.impl;

import cn.qayy.constants.Constant;
import cn.qayy.dao.RegisterMapper;
import cn.qayy.dto.BasisDTO;
import cn.qayy.dto.RegisterDTO;
import cn.qayy.po.Basis;
import cn.qayy.po.Register;
import cn.qayy.service.IRegisterService;
import cn.qayy.service.SynchronizationService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/***
 * @author wy
 *
 */
@Service("registerServiceImpl")
@SuppressWarnings("all")
public class RegisterServiceImpl implements IRegisterService {
	private Logger logger = LoggerFactory.getLogger(RegisterServiceImpl.class);
	@Resource
	private RegisterMapper registerMapper;
	
	@Resource(name = "synchronizationImpl")
	private SynchronizationService synchronizationService;

	@Override
	public PageInfo<Map<String, Object>> selectRegisterBy(Map<String, Object> params) {
		if (params != null && params.size() > 0) {
			DownLoadUtil.set("RegisterDTO",params);
			if (params.containsKey("pageNumber") && params.containsKey("pageSize")) {
				Integer pageNum = Integer.parseInt((String) params.get("pageNumber"));
				Integer pageSize = Integer.parseInt((String) params.get("pageSize"));
				PageHelper.startPage(pageNum, pageSize);
			}
			List<Map<String, Object>> list = registerMapper.selectRegisterBy(params);
			PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public int insertByList(List forList) {
		return registerMapper.insertByList(forList);
	}

	@Override
	public List<Map<String, String>> selectCommercialSourceAuto() {
		return registerMapper.selectCommercialSourceAuto();
	}

	// @Override
	public int updateRegisterByID(@RequestParam Map<String, Object> params) {
		Register register = new Register();
		register.setId(Integer.parseInt(String.valueOf(params.get("id"))));
		register.setZhengheqs(params.get("qsname").toString());
		register.setTerminaltype(params.get("terminaltype").toString());
		register.setAddr(params.get("addr").toString());
		register.setMemo(params.get("memo").toString());
		register.setCountry(params.get("county").toString());
		register.setCity(params.get("city").toString());
		register.setTerminallve(params.get("terminallve").toString());
		register.setCname(params.get("terminal").toString()); // 入货乙方
		register.setShengfen(params.get("province").toString());
		System.out.println("register:" + register.toString());

		return registerMapper.updateByPrimaryKeySelective(register);
	}

	@Override
	public Register selectRegisterByID(@RequestParam Integer planId) {
		return registerMapper.selectByPrimaryKey(planId);
	}

	// @Override
	public int addRegister(@RequestParam Map<String, Object> params) {
		Register register = new Register();
		// register.setId(Integer.parseInt(String.valueOf(params.get("id"))));
		register.setZhengheqs(params.get("qsname").toString());
		register.setTerminaltype(params.get("terminaltype").toString());
		register.setAddr(params.get("addr").toString());
		register.setMemo(params.get("memo").toString());
		register.setCountry(params.get("county").toString());
		register.setCity(params.get("city").toString());
		register.setTerminallve(params.get("terminallve").toString());
		register.setCname(params.get("terminal").toString()); // 入货乙方
		register.setShengfen(params.get("province").toString());
		System.out.println("addRegister:" + register.toString());
		return registerMapper.insertSelective(register);
	}

	@Override
	public List<Map<String, String>> selectAllJiafanAndYifan() {
		return registerMapper.selectAllJiafanAndYifan();
	}

	@Override
	public int updateByList(List list) {
		return registerMapper.updateByList(list);
	}

	@Override
	public int deleteByList(List list) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int insert(Object bean) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int update(Object bean) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int delete(Object bean) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public List<Register> selectJiafanAndYifanByNames(Map<String, Object> params) {
		return registerMapper.selectJiafanAndYifanByNames(params);
	}

	@Override
	public List<Register> selectAllProvince2Names() {
		return registerMapper.selectAllProvince2Names();
	}

	@Override
	public List<Register> selectByMap(Map<String, Object> params) throws Exception {
		return registerMapper.selectByMap(params);
	}

	@Override
	public List<Integer> selectIdsByMap(Map<String, Object> params) {
		return registerMapper.selectIdsByMap(params);
	}

	@Override
	public PageInfo<Register> selectForList(Map<String, Object> params) {
		if (params != null && params.size() > 0) {
			//下载时记住当时查询的条件
			DownLoadUtil.set("RegisterDTO",params);
			
			PageHelper.startPage(StringUtil.parseInt(params.get("pageNumber").toString()), StringUtil.parseInt(params.get("pageSize").toString()));
			List<Register> list = registerMapper.selectForList(params);
			PageInfo<Register> pageInfo = new PageInfo<Register>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public void persistence(Map<String, List<Uploadable>> map, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//获取更新的省份、地市、区县，用于同步更新
		Set<String> provinces = new HashSet<String>(Constant.INIT_CAPACITY*4);
		Set<String> citys = new HashSet<String>(Constant.SMALL_CAPACITY);
		Set<String> countrys = new HashSet<String>(Constant.SMALL_CAPACITY);
		
		List<Uploadable> listE = map.get("E");
		if(listE!=null && !listE.isEmpty()) {
			// 待更新的实体list
			List<Register> list = new ArrayList<Register>(listE.size()+1);
			
			List<Register> db_list = new ArrayList<Register>(listE.size()+1);
			List<String> ids = new ArrayList<String>(listE.size()+1);
			for (Uploadable u : listE) {
				RegisterDTO dto = (RegisterDTO)u;
				ids.add(dto.getId());
			}
			
			db_list = registerMapper.selectByIds(ids);
			//校验Excel上传的id是否正确
			if(ids.size() != db_list.size()) {
				throw new Exception(Constant.FAIL_MSG_ID);
			}
			
			//更新之前把旧的从缓存中移除
			List<Register> plist = new ArrayList<Register>();
			for (Uploadable u : listE) {
				RegisterDTO dto = (RegisterDTO)u;
				//获取更新的省份、地市、区县，用于同步更新/
				provinces.add(dto.getShengfen());
				citys.add(dto.getCity());
				countrys.add(dto.getCountry());
				for(Register r:db_list) {
					if(r.getId().toString().equals(dto.getId())) {
						plist.add(r);
						
						// 封装数据
						r.setByDTO(dto);
						//大区、片区、经理 是基础库同步的，在同步前，先初始化为空
						r.setProvince("");
						r.setSpace("");
						r.setMgr("");
						r.setToday(DateUtils.dateToString(new Date(),"yyyy/MM/dd HH:mm:ss"));
						r.setDataer(request.getSession().getAttribute("username").toString());
						list.add(r);
						continue;
					}
				}
			}
			if(!list.isEmpty()) {
				removeToContext(plist);
				try {
					registerMapper.updateByList(list);
				} catch (Exception e) {
					addToContext(plist);
					throw e;
				}
				addToContext(list);
			}
		}
		List<Uploadable> listN = map.get("N");
		if(listN!=null && !listN.isEmpty()) {
			//待新增的实体list
			List<Register> list = new ArrayList<Register>(listN.size()+1);
			for (Uploadable u : listN) {
				RegisterDTO dto = (RegisterDTO)u;
				//获取更新的省份、地市、区县，用于同步更新
				provinces.add(dto.getShengfen());
				citys.add(dto.getCity());
				countrys.add(dto.getCountry());
				//封装数据
				Register r = new Register();
				r.setByDTO(dto);
				r.setToday(DateUtils.dateToString(new Date(),"yyyy/MM/dd HH:mm:ss"));
				r.setDataer(request.getSession().getAttribute("username").toString());
				list.add(r);
			}
			if(!list.isEmpty()) {
				registerMapper.insertByList(list);
				addToContext(list);
			}
		}
		//同步更新流向 
		synchronizationService.syncUpdatePlansIgnoreXsCount(provinces, citys, countrys);
	}

	/***
     * 注册库注册后，更新context缓存
     * @param list
     */
    private void addToContext(List<Register> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//注册库入货乙方
    	Set<String> cNames = (Set<String>)servletContext.getAttribute("cNames");
		for (Register b : list) {
			cNames.add(b.getCname());
		}
		//注册库入货乙方
		HashMap<String, Object> condiMap = (HashMap<String, Object>)servletContext.getAttribute("condiMap");
		condiMap.put("terminal", JSONObject.toJSONString(cNames));
    }
    /***
     * 注册库注册后，更新context缓存
     * @param list
     */
    private void removeToContext(List<Register> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//注册库入货乙方
    	Set<String> cNames = (Set<String>)servletContext.getAttribute("cNames");
    	for (Register b : list) {
    		cNames.remove(b.getCname());
    	}
    	//注册库入货乙方
    	HashMap<String, Object> condiMap = (HashMap<String, Object>)servletContext.getAttribute("condiMap");
    	condiMap.put("terminal", JSONObject.toJSONString(cNames));
    }
}
